import os

import numpy as np
from keras import Input, Model
from keras.applications.imagenet_utils import preprocess_input
from keras.applications.resnet50 import ResNet50
from keras.layers import Flatten, Dense
from keras.preprocessing import image

from dao import select_list, do_execute

IMAGE_SIZE = 224
base_img_dir = 'D:/cdn'
base_model = ResNet50(weights='imagenet', include_top=False, pooling='max',
                      input_tensor=Input(shape=(IMAGE_SIZE, IMAGE_SIZE, 3)))
x = base_model.output
feature = Dense(1024)(x)
model = Model(inputs=base_model.input, outputs=feature)
sql_product = 'select id from t_product'
pIDs = select_list(sql_product)

for pid in pIDs:
    sql_img = 'select * from t_image_info where productID=%d' % pid['id']
    img_info_list = select_list(sql_img)
    for img_info in img_info_list:
        location = img_info['location']
        if location.startswith('desc'):
            img_path = os.path.join(base_img_dir, location)
            if os.path.exists(img_path):
                print(pid['id'], img_path)
                img = image.load_img(img_path, target_size=(IMAGE_SIZE, IMAGE_SIZE))
                x = image.img_to_array(img)
                x = np.expand_dims(x, axis=0)
                x = preprocess_input(x)
                features = model.predict(x)
                # print(features.shape)
                # print(features)
                str_features = ','.join(str(j) for j in features[0])
                # print(str_features)
                sql_update = "update t_image_info set features = '%s' where ID = %d" % (str_features, img_info['ID'])
                do_execute(sql_update)
